/**
 * @Title:  AuthMechanismActivity.java 
 * @Copyright:  XXX Co., Ltd. Copyright YYYY-YYYY,  All rights reserved 
 * @Description:  TODO<请描述此文件是做什么的> 
 * @author:  MeiYi 
 * @data:  2016-1-5 上午11:24:06 
 * @version:  V1.0 
 */

package artid.com.arttogo.fragment;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.R.anim;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;

import artid.com.arttogo.R;
import artid.com.arttogo.activity.ArtMallActivity;
import artid.com.arttogo.activity.MallDetailPagerActivity;
import artid.com.arttogo.adapter.MallListAdapter;
import artid.com.arttogo.bean.ArtistgoodsList;
import artid.com.arttogo.bean.GoodsList;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.network.BitmapCache;
import artid.com.arttogo.network.VolleyBasic;
import artid.com.arttogo.network.VolleyCallback;
import artid.com.arttogo.network.VolleyData;
import artid.com.arttogo.network.VolleyMap;
import artid.com.arttogo.utils.NetUtils;
import artid.com.arttogo.view.pulllist.PullToRefreshLayout;
import artid.com.arttogo.view.pulllist.PullableListView;
import artid.com.arttogo.view.pulllist.PullableScrollView;
import artid.com.arttogo.view.xlistview.PLA_AbsListView;
import artid.com.arttogo.view.xlistview.PLA_AdapterView;
import artid.com.arttogo.view.xlistview.XListView;

/**
 * TODO<艺术家动态>
 * 
 * @author 熊彬
 * @data: 2016-1-5 上午11:24:06
 * @version: V1.0
 */
public class CollecterOnsaleActivity extends BaseFragment {
	private View mView;
	private Context mContext;
    private XListView mListView;
    private List<GoodsList> list;
    private MallListAdapter adapter;
    LinearLayout blankView;
	private PullableScrollView scrollView;
	String id;
	private ImageLoader mImageLoader;
	PullToRefreshLayout mPullLayout;
	int pageIndex = 1,pagesize = 10;
	LayoutInflater inflater;
	View hint;

    private String imgwide;// 请求的图片宽度
    private int dataNum;//数据总条数
    private Boolean isLoad = true;//是否加载数据（默认可以加载）
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.sigmatrix.artworkart.BaseActivity#onCreate(android.os.Bundle)
	 */

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		Bundle args = getArguments();
		id = args != null ? args.getString("id") : "";
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		this.inflater = inflater;
		mView = inflater.inflate(R.layout.activity_collecter_onsale, null);
		mContext = getActivity();

        imgwide = (Integer.parseInt(NetUtils.getDisplayMetrics((Activity) mContext).get(NetUtils.DM_WIDTH)) / 2) + "";
        blankView = (LinearLayout)mView.findViewById(R.id.ll_hint);
        ImageView imageBlank = (ImageView)blankView.findViewById(R.id.img_blank);
        imageBlank.setImageResource(R.drawable.blank_mall);
        ViewGroup.LayoutParams lp = imageBlank.getLayoutParams();
        lp.width = RelativeLayout.LayoutParams.WRAP_CONTENT;
        lp.height = RelativeLayout.LayoutParams.WRAP_CONTENT;
        imageBlank.setLayoutParams(lp);
        blankView.setVisibility(View.GONE);
        TextView textBlank = (TextView)blankView.findViewById(R.id.text_blank);
        textBlank.setText("暂无出售商品");
        DisplayMetrics dm = new DisplayMetrics();

        mListView = (XListView) mView.findViewById(R.id.ArtMall_listivew);
        mListView.setVisibility(View.GONE);
        mListView.setPullRefreshEnable(true);
        mListView.setPullLoadEnable(true);
        mListView.setXListViewListener(mIXListViewListener);
        mListView.setOnScrollListener(mOnScrollListener);
//        listview = (ListView) findViewById(R.id.listview1);
        RequestQueue mQueue = Volley.newRequestQueue(mContext);
        mImageLoader = new ImageLoader(mQueue, new BitmapCache());

        loading = (RelativeLayout) mView.findViewById(R.id.rel_progressbar);
        loading.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                System.out.println("#zhebiceng");
            }
        });

        requestGradeList(true);
		return mView;
	}

    //实现瀑布流下拉刷新上拉加载监听
    XListView.IXListViewListener mIXListViewListener = new XListView.IXListViewListener() {
        @Override
        public void onRefresh() {
            // 下拉刷新
            pageIndex++;
            requestGradeList(true);
        }

        @Override
        public void onLoadMore() {
            // 上拉加载
            pageIndex = 1;
            requestGradeList(false);
        }
    };

    //实现瀑布流滑动监听
    XListView.OnScrollListener mOnScrollListener = new XListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(PLA_AbsListView view, int scrollState) {

        }

        @Override
        public void onScroll(PLA_AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if(list!=null && list.size()!=0) {
                Log.d("log","firstVisibleItem:"+firstVisibleItem+"===visibleItemCount:"+visibleItemCount+"===totalItemCount:"+totalItemCount);
                if (list.size() != dataNum && isLoad == true) {
                    //-11是数据已经显示一半的时候如果加头了就-12
                    //-12是数据已经显示一半的时候（因为是瀑布流并且加了头所以-12）
                    if (pageIndex == 1 && firstVisibleItem == (pagesize - 11)) {
                        pageIndex++;
                        requestGradeList(false);
                    } else if (((pageIndex * pagesize) - 11) == firstVisibleItem) {
                        pageIndex++;
                        requestGradeList(false);
                    }
                }
            }
        }
    };



    View headView = null;
    JSONObject mainJson;
    JSONArray mainJSONArr;
    private void requestGradeList(Boolean isLoadDialog) {
        isLoad = false;
        if (isLoadDialog) {
            VolleyBasic.showLoding(mContext);
        }
        VolleyBasic.getInstanceNoDialog((Activity) mContext).post(Cache.artistgoodsList, VolleyMap.getInstance().artistgoodsList(id,String.valueOf(pageIndex),String.valueOf(pagesize),imgwide), GoodsList.class,
                new VolleyCallback() {

                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        isLoad = true;
                        mListView.stopRefresh();
                        mListView.stopLoadMore();
                        list = (List<GoodsList>) vd.getList();
                        JSONObject jsonString = vd.getObj();
                        JSONArray jsonArray = jsonString.optJSONArray("data");
                        if (list.isEmpty()) {
                            if (pageIndex==1) {
                                mListView.setVisibility(View.INVISIBLE);
                                blankView.setVisibility(View.VISIBLE);
                            }
                            return;
                        }
                        mListView.setVisibility(View.VISIBLE);
                        blankView.setVisibility(View.GONE);
                        if (mListView.getVisibility()==View.INVISIBLE) {
                            mListView.setVisibility(View.VISIBLE);
                        }
                        if(pageIndex==1) {
                            try {
                                JSONObject jsonObject = new JSONObject(vd.getJson());
                                dataNum = jsonObject.getInt("num");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        if (pageIndex!=1) {
                            try {
                                if (jsonArray==null) {
                                    return;
                                }
                                for (int i = 0; i < jsonArray.length(); i++) {

                                    mainJSONArr.put(jsonArray.get(i));

                                }
                                mainJson.remove("data");
                                mainJson.put("data", mainJSONArr);
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                            adapter.addlist(list);
                            setItemClick(mainJson.toString());
                            return;
                        }
                        mainJson = jsonString;
                        mainJSONArr = jsonArray;
                        adapter = new MallListAdapter(mContext);
                        adapter.setdata(list);
                        mListView.setAdapter(adapter);
                        setItemClick(vd.getJson());

                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub
                        isLoad = true;
                        mListView.stopRefresh();
                        mListView.stopLoadMore();
                    }
                });
    }



    void setItemClick(final String json){
        mListView.setOnItemClickListener(new PLA_AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(PLA_AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(mContext, MallDetailPagerActivity.class);
                intent.putExtra("id",json);
                intent.putExtra("index", position-1);
                startActivity(intent);
            }
        });
    }



//	void reqAtristListData() {
//		VolleyBasic.getInstance((Activity)mContext).post(
//				Cache.artistgoodsList,
//				VolleyMap.getInstance().artistgoodsList(id, String.valueOf(pageIndex), String.valueOf(pagesize), "400"),
//				ArtistgoodsList.class, new VolleyCallback() {



}
